// 博客文章相关功能模块

let currentEditingPostId = null;

// 加载博客列表
function loadBlogList() {
    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=get_blog_list'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const blogList = data.data || [];
                const blogListContainer = document.getElementById('blog-list');

                // 清空列表
                blogListContainer.innerHTML = '';

                if (blogList.length === 0) {
                    blogListContainer.innerHTML = `
                <div class="placeholder">
                    <i class="fas fa-file-alt"></i>
                    <p>暂无博客文章</p>
                </div>
                `;
                } else {
                    // 获取分区列表用于显示分区名称
                    fetch('../BlogMake.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: 'action=get_site_config'
                    })
                        .then(response => response.json())
                        .then(configData => {
                            const partitions = configData.success ? configData.data.partitions || [] : [];

                            // 排序博客（按时间倒序）
                            blogList.sort((a, b) => new Date(b.time) - new Date(a.time));

                            // 渲染博客列表
                            blogList.forEach(post => {
                                const partition = partitions.find(p => p.id === post.partition);
                                const postItem = document.createElement('div');
                                postItem.className = 'post-item';
                                postItem.innerHTML = `
                        <div class="post-header">
                            <h3 class="post-title">${post.title}</h3>
                            <div class="post-actions">
                                <button class="btn btn-secondary btn-sm" onclick="openPostEditor(${post.id})">编辑</button>
                                <button class="btn btn-danger btn-sm" onclick="deletePost(${post.id})">删除</button>
                            </div>
                        </div>
                        <div class="post-meta">
                            <span>作者: ${post.author}</span>
                            <span>发布时间: ${post.time}</span>
                            <span>分区: ${partition ? partition.title : '未分类'}</span>
                            ${post.tags && post.tags.length > 0 ? `<span>标签: ${post.tags.join(', ')}</span>` : ''}
                        </div>
                        `;
                                blogListContainer.appendChild(postItem);
                            });
                        })
                        .catch(error => {
                            console.error('加载分区信息失败:', error);
                            // 即使分区信息加载失败，也要显示博客列表
                            blogList.sort((a, b) => new Date(b.time) - new Date(a.time));
                            blogList.forEach(post => {
                                const postItem = document.createElement('div');
                                postItem.className = 'post-item';
                                postItem.innerHTML = `
                        <div class="post-header">
                            <h3 class="post-title">${post.title}</h3>
                            <div class="post-actions">
                                <button class="btn btn-secondary btn-sm" onclick="openPostEditor(${post.id})">编辑</button>
                                <button class="btn btn-danger btn-sm" onclick="deletePost(${post.id})">删除</button>
                            </div>
                        </div>
                        <div class="post-meta">
                            <span>作者: ${post.author}</span>
                            <span>发布时间: ${post.time}</span>
                            <span>分区: 未分类</span>
                            ${post.tags && post.tags.length > 0 ? `<span>标签: ${post.tags.join(', ')}</span>` : ''}
                        </div>
                        `;
                                blogListContainer.appendChild(postItem);
                            });
                        });
                }
                showStatus('博客列表加载成功', 'success');
            } else {
                showStatus('加载博客列表失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('加载博客列表失败:', error);
            showStatus('加载博客列表失败', 'error');
        });
}

// 初始化帖子编辑器
function initPostEditor() {
    // 编辑器和预览切换
    document.getElementById('editor-tab')?.addEventListener('click', function () {
        this.classList.add('active');
        document.getElementById('preview-tab')?.classList.remove('active');
        const editorContent = document.getElementById('editor-content');
        if (editorContent) editorContent.style.display = 'block';
        const previewContent = document.getElementById('preview-content');
        if (previewContent) previewContent.style.display = 'none';
    });

    document.getElementById('preview-tab')?.addEventListener('click', function () {
        this.classList.add('active');
        document.getElementById('editor-tab')?.classList.remove('active');
        const editorContent = document.getElementById('editor-content');
        if (editorContent) editorContent.style.display = 'none';
        const previewContent = document.getElementById('preview-content');
        if (previewContent) previewContent.style.display = 'block';
        updatePostPreview();
    });

    // 关闭帖子编辑器
    document.getElementById('close-editor')?.addEventListener('click', function () {
        const postEditorModal = document.getElementById('post-editor-modal');
        if (postEditorModal) postEditorModal.style.display = 'none';
        currentEditingPostId = null;
    });

    // 保存帖子
    document.getElementById('save-post')?.addEventListener('click', function () {
        savePost();
    });

    // 删除当前帖子
    document.getElementById('delete-current-post')?.addEventListener('click', function () {
        if (currentEditingPostId) {
            deletePost(currentEditingPostId, true);
        }
    });

    // 关闭编辑器按钮
    document.getElementById('close-editor-btn')?.addEventListener('click', function () {
        const postEditorModal = document.getElementById('post-editor-modal');
        if (postEditorModal) postEditorModal.style.display = 'none';
        currentEditingPostId = null;
    });
}

// 打开帖子编辑器
function openPostEditor(postId = null) {
    currentEditingPostId = postId;

    // 清空编辑器
    document.getElementById('edit-post-title').value = '';
    document.getElementById('edit-post-author').value = '';
    document.getElementById('edit-post-time').value = new Date().toISOString().split('T')[0];
    document.getElementById('edit-post-content').value = '';
    document.getElementById('edit-post-tags').value = '';

    // 获取分区列表
    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=get_site_config'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const partitions = data.data.partitions || [];
                const partitionSelect = document.getElementById('edit-post-partition');

                // 清空分区选择
                partitionSelect.innerHTML = '';

                // 添加所有分区
                if (partitions.length === 0) {
                    // 如果没有分区，添加默认未分区选项
                    const defaultOption = document.createElement('option');
                    defaultOption.value = '0';
                    defaultOption.textContent = '未分区';
                    partitionSelect.appendChild(defaultOption);
                } else {
                    // 添加未分区选项
                    const defaultOption = document.createElement('option');
                    defaultOption.value = '0';
                    defaultOption.textContent = '未分区';
                    partitionSelect.appendChild(defaultOption);

                    // 添加所有实际分区
                    partitions.forEach(partition => {
                        const option = document.createElement('option');
                        option.value = partition.id;
                        option.textContent = partition.title;
                        partitionSelect.appendChild(option);
                    });
                }

                // 如果是编辑模式，加载帖子内容
                if (postId) {
                    // 获取帖子内容
                    fetch('../BlogMake.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: 'action=get_blog_list'
                    })
                        .then(response => response.json())
                        .then(blogListResult => {
                            if (blogListResult.success) {
                                fetch('../BlogMake.php', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded'
                                    },
                                    body: 'action=get_post_content&id=' + postId
                                })
                                    .then(response => response.json())
                                    .then(postContentResult => {
                                        const blogList = blogListResult.data || [];
                                        const post = blogList.find(p => p.id === postId);

                                        if (post) {
                                            document.getElementById('edit-post-title').value = post.title || '';
                                            document.getElementById('edit-post-author').value = post.author || '';
                                            document.getElementById('edit-post-time').value = post.time || new Date().toISOString().split('T')[0];

                                            // 设置分区
                                            const partitionSelect = document.getElementById('edit-post-partition');
                                            partitionSelect.value = post.partition || 1;

                                            // 设置内容
                                            document.getElementById('edit-post-content').value = postContentResult.content || '';

                                            // 设置标签
                                            document.getElementById('edit-post-tags').value = post.tags ? post.tags.join(', ') : '';
                                        }
                                    });
                            }
                        });
                }

                // 显示编辑器
                document.getElementById('post-editor-modal').style.display = 'flex';
            }
        });
}

// 更新帖子预览
function updatePostPreview() {
    const title = document.getElementById('edit-post-title').value;
    const author = document.getElementById('edit-post-author').value;
    const time = document.getElementById('edit-post-time').value;
    const partitionSelect = document.getElementById('edit-post-partition');
    const partition = partitionSelect.options[partitionSelect.selectedIndex]?.text || '未分类';
    const tags = document.getElementById('edit-post-tags').value;
    const content = document.getElementById('edit-post-content').value;

    // 生成预览HTML
    let previewHtml = `
    <div style="margin-bottom:16px;">
        <h2 style="color:var(--accent);margin-bottom:8px;">${title || '无标题'}</h2>
        <div style="display:flex;flex-wrap:wrap;gap:12px;color:var(--text-secondary);font-size:0.9em;">
            ${author ? `<span>作者: ${author}</span>` : ''}
            ${time ? `<span>发布时间: ${time}</span>` : ''}
            <span>分区: ${partition}</span>
            ${tags ? `<span>标签: ${tags}</span>` : ''}
        </div>
    </div>
    <div style="border-top:1px solid rgba(255,255,255,.08);padding-top:16px;">
    `;

    // 简单的Markdown解析
    let contentHtml = content
        .replace(/^# (.*$)/gm, '<h1 style="color:var(--accent);margin-bottom:16px;">$1</h1>')
        .replace(/^## (.*$)/gm, '<h2 style="color:var(--accent);margin-bottom:12px;">$1</h2>')
        .replace(/^### (.*$)/gm, '<h3 style="color:var(--accent);margin-bottom:8px;">$1</h3>')
        .replace(/\n\n/g, '</p><p>')
        .replace(/\n/g, '<br>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
        .replace(/`(.*?)`/g, '<code>$1</code>')
        .replace(/^\- (.*$)/gm, '<ul><li>$1</li></ul>')
        .replace(/<\/ul>\s*<ul>/g, '')
        .replace(/^\d\. (.*$)/gm, '<ol><li>$1</li></ol>')
        .replace(/<\/ol>\s*<ol>/g, '')
        .replace(/\n\n/g, '</p><p>');

    // 确保链接在新标签页打开
    contentHtml = contentHtml
        .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>');

    // 更新预览内容
    document.getElementById('preview-content').innerHTML = previewHtml + contentHtml + '</div>';
}

// 保存帖子
function savePost() {
    const title = document.getElementById('edit-post-title').value;
    const author = document.getElementById('edit-post-author').value;
    const time = document.getElementById('edit-post-time').value;
    const partition = document.getElementById('edit-post-partition').value;
    const content = document.getElementById('edit-post-content').value;
    const tags = document.getElementById('edit-post-tags').value.split(',').map(tag => tag.trim()).filter(tag => tag);

    // 验证必填项
    if (!title) {
        showStatus('标题不能为空', 'error');
        return;
    }

    if (!author) {
        showStatus('作者不能为空', 'error');
        return;
    }

    if (!content) {
        showStatus('内容不能为空', 'error');
        return;
    }

    if (currentEditingPostId) {
        // 更新现有帖子
        const title = document.getElementById('edit-post-title').value;
        const author = document.getElementById('edit-post-author').value;
        const time = document.getElementById('edit-post-time').value;
        const partition = document.getElementById('edit-post-partition').value;
        const content = document.getElementById('edit-post-content').value;
        const tags = document.getElementById('edit-post-tags').value.split(',').map(tag => tag.trim()).filter(tag => tag);

        // 保存帖子内容
        fetch('../BlogMake.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'action=save_post_content&id=' + currentEditingPostId + '&content=' + encodeURIComponent(content)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新博客列表中的信息
                    fetch('../BlogMake.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: 'action=get_blog_list'
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const blogList = data.data || [];
                                const postIndex = blogList.findIndex(p => p.id === currentEditingPostId);

                                if (postIndex !== -1) {
                                    blogList[postIndex].title = title;
                                    blogList[postIndex].author = author;
                                    blogList[postIndex].time = time;
                                    blogList[postIndex].partition = parseInt(partition);
                                    blogList[postIndex].tags = tags;

                                    // 保存更新后的博客列表
                                    fetch('../BlogMake.php', {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/x-www-form-urlencoded'
                                        },
                                        body: 'action=save_blog_list&blogList=' + encodeURIComponent(JSON.stringify(blogList))
                                    })
                                        .then(response => response.json())
                                        .then(data => {
                                            if (data.success) {
                                                const postEditorModal = document.getElementById('post-editor-modal');
                                                if (postEditorModal) postEditorModal.style.display = 'none';
                                                currentEditingPostId = null;
                                                loadBlogList();
                                                showStatus('帖子更新成功', 'success');
                                            } else {
                                                showStatus('更新博客列表失败: ' + data.message, 'error');
                                            }
                                        });
                                } else {
                                    showStatus('未找到该帖子', 'error');
                                }
                            } else {
                                showStatus('获取博客列表失败: ' + data.message, 'error');
                            }
                        });
                } else {
                    showStatus('保存帖子内容失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('保存帖子失败:', error);
                showStatus('保存帖子失败', 'error');
            });
    } else {
        // 创建新帖子
        // 首先获取博客列表，找到最大的ID
        fetch('../BlogMake.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'action=get_blog_list'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    let blogList = data.data || [];
                    let newPostId = 1;

                    if (blogList.length > 0) {
                        newPostId = Math.max(...blogList.map(p => p.id)) + 1;
                    }

                    // 创建新帖子对象
                    const newPost = {
                        id: newPostId,
                        title: title,
                        author: author,
                        time: time,
                        partition: parseInt(partition),
                        tags: tags
                    };

                    // 添加到博客列表
                    blogList.push(newPost);

                    // 保存博客列表
                    fetch('../BlogMake.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: 'action=save_blog_list&blogList=' + encodeURIComponent(JSON.stringify(blogList))
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // 保存帖子内容
                                fetch('../BlogMake.php', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded'
                                    },
                                    body: 'action=save_post_content&id=' + newPostId + '&content=' + encodeURIComponent(content)
                                })
                                    .then(response => response.json())
                                    .then(data => {
                                        if (data.success) {
                                            const postEditorModal = document.getElementById('post-editor-modal');
                                            if (postEditorModal) postEditorModal.style.display = 'none';
                                            currentEditingPostId = null;
                                            loadBlogList();
                                            showStatus('帖子创建成功', 'success');
                                        } else {
                                            showStatus('保存帖子内容失败: ' + data.message, 'error');
                                        }
                                    });
                            } else {
                                showStatus('保存博客列表失败: ' + data.message, 'error');
                            }
                        });
                } else {
                    showStatus('获取博客列表失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('创建新帖子失败:', error);
                showStatus('创建新帖子失败', 'error');
            });
    }
}

// 删除帖子
function deletePost(postId, closeEditor = false) {
    if (!confirm('确定要删除这篇帖子吗？此操作无法撤销。')) {
        return;
    }

    // 先删除帖子内容
    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=delete_post&id=' + postId
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 然后从博客列表中移除
                fetch('../BlogMake.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: 'action=get_blog_list'
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            let blogList = data.data || [];

                            // 过滤掉要删除的帖子
                            blogList = blogList.filter(p => p.id !== postId);

                            // 保存更新后的博客列表
                            return fetch('../BlogMake.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                },
                                body: 'action=save_blog_list&blogList=' + encodeURIComponent(JSON.stringify(blogList))
                            });
                        } else {
                            throw new Error('获取博客列表失败');
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            if (closeEditor) {
                                const postEditorModal = document.getElementById('post-editor-modal');
                                if (postEditorModal) postEditorModal.style.display = 'none';
                                currentEditingPostId = null;
                            }
                            loadBlogList();
                            showStatus('帖子删除成功', 'success');
                        } else {
                            showStatus('保存博客列表失败: ' + data.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('删除帖子失败:', error);
                        showStatus('删除帖子失败', 'error');
                    });
            } else {
                showStatus('删除帖子内容失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('删除帖子失败:', error);
            showStatus('删除帖子失败', 'error');
        });
}